import React, { useEffect, useMemo, useState } from "react";
import TrainItem from "./TrainItem";
import { useLoaderData, useSearchParams } from "react-router-dom";
import { Button, InfiniteScroll, Tabs } from "antd-mobile";
import { getTrainListApi } from "../../../api/train";
import dayjs from "dayjs";
import styles from "../css/list.module.css";
function TrainList() {
  const { list } = useLoaderData();
  const [trainList, setTrainList] = useState(list);
  const [page, setPage] = useState(2);
  const [sp, setSp] = useSearchParams();
  const spObj = useMemo(() => Object.fromEntries(sp), [sp]);
  const setDate = (num) => {
    let now = dayjs(sp.get("date")).add(num, "day").format("YYYY-MM-DD");
    setSp({ ...spObj, date: now });
  };
  const [hasMore, setHasMore] = useState(true);
  async function loadMore() {
    const { data: list } = await getTrainListApi({ ...spObj, page });
    setTrainList((prev) => [...prev, ...list]);
    setPage((prev) => prev + 1);
    if (list.length === 0) {
      setHasMore(false);
    }
  }
  useEffect(() => {
    window.scrollTo({ top: 0 });
    setTrainList(list);
    setPage(2);
    setHasMore(true);
  }, [list]);
  return (
    <div>
      <div className={styles.date}>
        <Button
          style={{ color: "#fff" }}
          fill="none"
          size="mini"
          onClick={() => setDate(-1)}
          disabled={
            Math.ceil(dayjs(sp.get("date")).diff(dayjs(), "day", true)) <= 0
          }
        >
          前一天
        </Button>
        <span>{sp.get("date")}</span>
        <Button
          style={{ color: "#fff" }}
          fill="none"
          size="mini"
          onClick={() => setDate(1)}
          disabled={
            Math.ceil(dayjs(sp.get("date")).diff(dayjs(), "day", true)) >= 4
          }
        >
          后一天
        </Button>
      </div>
      <Tabs className={styles.Tabs}>
        <Tabs.Tab title="火车" key="fruits">
          
        </Tabs.Tab>
        <Tabs.Tab title="飞机" key="vegetables">
          
        </Tabs.Tab>
        <Tabs.Tab title="汽车" key="animals">
          
        </Tabs.Tab>
      </Tabs>
      {trainList.map((item) => (
            <TrainItem key={item.id} {...item} />
          ))}
          <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  );
}

export default TrainList;
